import React, { Component } from "react";
import {
  Form,
  Input,
  Select,
  Table,
  Divider,
  Button,
  Modal,
  DatePicker,
  Popconfirm,
  Row,
  Col
} from "antd";
import Content from "../../components/Content/Content";
import moment from "moment";
const { RangePicker } = DatePicker;
const { Item } = Form;
const { confirm } = Modal;
const { Option } = Select;
const { TextArea } = Input;
const InputGroup = Input.Group;

//表格内容数据
const dataSource = [];
for (let i = 0; i < 30; i++) {
  dataSource.push({
    key: i,
    name: `AACC000${i}`,
    number: `${i}`,
    date: `2019/9/${i}`,
    age4: `AACC000${i}`
  });
}

class Query_mediumForm extends Component {
  state = {
    dataSource: dataSource,
    count: 0,

    viewData: {},
    editData: {},
    newData: {},
    searchParams: {},

    filteredInfo: null,
    sortedInfo: null,
    selectedRowKeys: [],

    loading_out_to_first: false,
    loading_out_to_local: false,

    showViewModal: false,
    showEditModal: false,
    showAddModal: false
  };

  handleChange = (pagination, filters, sorter) => {
    console.log("Various parameters", pagination, filters, sorter);
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter
    });
  };

  onSelectChange = selectedRowKeys => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  //导出到初筛
  outToFirst = () => {
    this.setState({ loading_out_to_first: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out_to_first: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   

  };
  
  // 导出到本地
  outToLocal = () => {
    this.setState({ loading_out_to_local: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out_to_local: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   

  };

  //Modal
  showViewModal(showViewModal, viewData = {}) {
    this.setState({ showViewModal, viewData: viewData });
  }
  showEditModal(showEditModal, editData ={}) {
    this.setState({ showEditModal, editData: editData });
  }
  showAddModal(showAddModal) {
    this.setState({ showAddModal });
  }

  // 删除
  handleDelete = (id) => {
    const url = global.api.crudeextractInfo + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.loadData(1);

      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    })    
  }

  // 更新
  handleUpdate = () => {
    const url = global.api.crudeextractInfo + this.state.editData.id + '/';
    return global.updatedata.put(url, this.state.editData)
    .then(res => {  
      this.loadData(1);

      Modal.success({
        content: '更新成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '更新出错!',
      });
    })    
  }

  // 保存
  handleAdd = () => {
    const url = global.api.crudeextractInfo;
    return global.network.post(url, this.state.newData)
    .then(res => {  
      this.loadData(1);
      
      Modal.success({
        content: '保存成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '保存出错!',
      });
    })    
  }

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    let { searchParams } = this.state;
    let params = {
      page_index: current, 
      page_size: this.state.pageSize, 
      ctp_id:searchParams.ctp_id || "",
      f_fjypid: searchParams.f_fjypid || "",
      id: searchParams.id || "",
      sxjj_id: searchParams.sxjj_id || "",
      jzbc_id: searchParams.jzbc_id || "",
      ferment_time: searchParams.ferment_time || "",
      ferment_batch: searchParams.ferment_batch || "",
      ce_cqrj: searchParams.ce_cqrj || "",
      ce_cqbw: searchParams.ce_cqbw || "",
      m_id:  searchParams.m_id || "",
      ce_time:  searchParams.ce_time || "",
      ce_person:  searchParams.ce_person || ""
    }

    const url = global.api.crudeextractInfo;
    return global.getdata.get(url, params)
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  render() {
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    //表格表头数据
    const columns = [
      {
        title: "ID",
        width: 120,
        fixed: "left",
        key: "id",
        dataIndex: "id"
      },
      {
        title: "粗提品编号",
        key: "ctp_id",
        dataIndex: "ctp_id",
        fixed: "left",
        width: 200,
        sorter: (a, b) => a.name.replace(/[^\d.]/g, "") - b.name.replace(/[^\d.]/g, ""),
        sortOrder: sortedInfo.columnKey === "ctp_id" && sortedInfo.order
      },
      {
        title: "发酵液样品编号",
        key: "f_fjypid",
        dataIndex: "f_fjypid",
        sorter: (a, b) => a.number - b.number,
        sortOrder: sortedInfo.columnKey === "f_fjypid" && sortedInfo.order
      },
      {
        title: "筛选菌株编号",
        key: "sxjj_id",
        dataIndex: "sxjj_id"
      },
      {
        title: "菌种保藏编号",
        key: "jzbc_id",
        dataIndex: "jzbc_id"
      },
      {
        title: "发酵日期",
        key: "ferment_time",
        dataIndex: "ferment_time"
      },
      {
        title: "发酵批号",
        key: "ferment_batch",
        dataIndex: "ferment_batch"
      },
      {
        title: "萃取溶剂",
        key: "ce_cqrj",
        dataIndex: "ce_cqrj"
      },
      {
        title: "萃取部位",
        key: "ce_cqbw",
        dataIndex: "ce_cqbw"
      },

      {
        title: "筛选模型编号",
        key: "m_id",
        dataIndex: "m_id"
      },
      {
        title: "粗提品制备时间",
        key: "ce_time",
        dataIndex: "ce_time"
      },
      {
        title: "粗提品制备人",
        key: "ce_person",
        dataIndex: "ce_person"
      },
      {
        title: "母板存放位置",
        key: "mom_place",
        dataIndex: "mom_place"
      },
      {
        title: "母板粗提品量/(微升)",
        key: "ce_mbctp",
        dataIndex: "ce_mbctp"
      },
      {
        title: "子板存放位置",
        key: "son_place",
        dataIndex: "son_place"
      },

      {
        title: "子板粗提品量/(微升)",
        key: "ce_zbctp",
        dataIndex: "ce_zbctp"
      },
      {
        title: "工作人员姓名",
        key: "worker",
        dataIndex: "worker"
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        fixed: "right",
        width: 300,
        render: (text, record) => (
          <span>
            <Button type="dashed" onClick={() => this.showViewModal(true, record)}>
              查看
            </Button>
            <Divider type="vertical" />
            <Button type="dashed" onClick={() => this.showEditModal(true, record)}>
              修改
            </Button>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
                <Button type="dashed" >删除</Button>
            </Popconfirm>
          </span>
        )
      }
    ];

    //全部选中/取消全选
    const { loading_out_to_first, loading_out_to_local, selectedRowKeys, count } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      selections: [
        {
          key: "allData",
          text: "全部选中",
          onSelect: () => {
            this.setState({
              selectedRowKeys: [...Array(count).keys()] // 0...29
            });
          }
        },
        {
          key: "nullData",
          text: "取消全选",
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          }
        }
      ]
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <div>
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >

          <div style={{ display: "flex" }}>
            <span style={{ flex: 1 }}>
              <Item label="粗提品编号">
                <Input onChange={e => this.state.searchParams.ctp_id = e.target.value} />
              </Item>
              <Item label="发酵液样品编号">
                <Input onChange={e => this.state.searchParams.f_fjypid = e.target.value} />
              </Item>
              <Item label="粗提品ID">
                <Input onChange={e => this.state.searchParams.id = e.target.value} />
              </Item>
              <Item label="筛选菌株编号">
                <Input onChange={e => this.state.searchParams.sxjj_id = e.target.value} />
              </Item>
            </span>
            <span style={{ flex: 1 }}>
              <Item label="菌种保藏编号">
                <Input onChange={e => this.state.searchParams.jzbc_id = e.target.value} />
              </Item>
              <Item label="发酵日期">
                <DatePicker
                  onChange={(date, dateString) => this.state.searchParams.ferment_time = dateString}
                  style={{ width: "100%" }}
                  placeholder={[" ", ""]}
                />
              </Item>
              <Item label="发酵批号">
                <Input onChange={e => this.state.searchParams.ferment_batch = e.target.value} />
              </Item>
              <Item label="萃取溶剂">
                <Input onChange={e => this.state.searchParams.ce_cqrj = e.target.value} />
              </Item>
            </span>
            <span style={{ flex: 1 }}>
              <Item label="萃取部位">
                <Select
                  mode="tags"
                  style={{ width: "100%" }}
                  onChange={value => this.state.searchParams.ce_cqbw = value[0]}
                  tokenSeparators={[","]}
                  showArrow={true}
                >
                  <Option value="fjysq">发酵液上清</Option>
                  <Option value="fjyjt">发酵液菌体</Option>
                  <Option value="gtfjw">固体发酵物</Option>
                  <Option value="qtbw" disabled>
                  其他部位
                  </Option>
                </Select>
              </Item>
              <Item label="已筛选模型">
                <Input onChange={e => this.state.searchParams.m_id = e.target.value} />
              </Item>
              <Item label="粗提品制备时间">
                <DatePicker
                  onChange={(date, dateString) => this.state.searchParams.ce_time = dateString}
                  style={{ width: "100%" }}
                  placeholder={[" ", ""]}
                />
              </Item>
              <Item label="粗提品制备人">
                <Input onChange={e => this.state.searchParams.ce_person = e.target.value} />
              </Item>
            </span>
          </div>
          <Item wrapperCol={{ span: 10, offset: 2 }}>
            <Row guuter={16}>
              <Col span={5}>
                <Button onClick={()=>this.loadData(1)} type="primary" loading={this.state.loading}>
                  精确查询
                </Button>
              </Col>
              <Col span={5}>
              </Col>
              <Col span={5}>
              </Col>
            </Row>
          </Item>
        </Form>

        <Button
          type="primary"
          onClick={this.outToFirst}
          disabled={!hasSelected}
          loading={loading_out_to_first}
          style={{ marginLeft: 20, marginTop: 20 }}
        >
          导出到初筛
        </Button>
        <Button
          type="primary"
          onClick={this.outToLocal}
          disabled={!hasSelected}
          loading={loading_out_to_local}
          style={{ marginLeft: 20, marginTop: 20 }}
        >
          导出到本地
        </Button>
        <Button
          type="primary"
          onClick={() => this.showAddModal(true)}
          style={{ marginLeft: 20, marginTop: 20 }}
        >
          添加粗提品
        </Button>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `选中 ${selectedRowKeys.length} 个` : ""}
        </span>

        <div>
          <Modal
            title=" 查看 "
            centered
            visible={this.state.showViewModal}
            onOk={() => this.showViewModal(false)}
            onCancel={() => this.showViewModal(false)}
            maskClosable={false}
          >
            <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
              <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                  <Item label="粗提品编号">
                      <Input value={this.state.viewData.ctp_id } />
                  </Item>
                  <Item label="发酵液样品编号">
                      <Input value={this.state.viewData.f_fjypid } />
                  </Item>
                  <Item label="粗提品ID">
                      <Input value={this.state.viewData.id } />
                  </Item>
                  <Item label="筛选菌株编号">
                      <Input value={this.state.viewData.sxjj_id  } />
                  </Item>
                  <Item label="菌种保藏编号">
                      <Input value={this.state.viewData.jzbc_id  } />
                  </Item>

                  <Item label="发酵日期">
                      <Input value={this.state.viewData.ferment_time  } />
                  </Item>
                  <Item label="发酵批号">
                      <Input value={this.state.viewData.ferment_batch  } />
                  </Item>
                  <Item label="萃取溶剂">
                      <Input value={this.state.viewData.ce_cqrj  } />
                  </Item>
                  <Item label="萃取部位">
                    <Select
                      mode="tags"
                      style={{ width: "100%" }}
                      defaultValue={this.state.viewData.ce_cqbw}
                      tokenSeparators={[","]}
                      showArrow={true}
                    >
                      <Option value="fjysq">发酵液上清</Option>
                      <Option value="fjyjt">发酵液菌体</Option>
                      <Option value="gtfjw">固体发酵物</Option>
                      <Option value="qtbw" disabled>
                        其他部位
                      </Option>
                    </Select>
                  </Item>
                </span>
                <span style={{ flex: 1 }}>
                  <Item label="已筛选模型">
                      <Input value={this.state.viewData.m_id  } />
                  </Item>
                  <Item label="粗提品制备时间">
                      <Input value={this.state.viewData.ce_time  } />
                  </Item>
                  <Item label="粗提品制备人">
                      <Input value={this.state.viewData.ce_person  } />
                  </Item>
                  <Item label="母板存放位置">
                      <Input value={this.state.viewData.mom_place  } />
                  </Item>
                  <Item label="母板粗提品量/(微升)">
                      <Input value={this.state.viewData.ce_mbctp } />
                  </Item>
                  <Item label="子板存放位置">
                      <Input value={this.state.viewData.son_place  } />
                  </Item>
                  <Item label="子板粗提品量/(微升)">
                      <Input value={this.state.viewData.ce_zbctp } />
                  </Item>
                  <Item label="工作人员姓名">
                      <Input value={this.state.viewData.worker } />
                  </Item>
                 
                </span>

              </div>
            </Form>
          </Modal>
          <Modal
            title="修改"
            centered
            visible={this.state.showEditModal}
            onOk={() => this.showEditModal(false)}
            onCancel={() => this.showEditModal(false)}
            maskClosable={false}
          >
            <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
              <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                  <Item label="粗提品ID">
                      <Input defaultValue={this.state.editData.id } readOnly />
                  </Item>
                <Item label="粗提品编号">
                      <Input defaultValue={this.state.editData.ctp_id } onChange={e => this.state.editData.ctp_id = e.target.value } />
                  </Item>
                  <Item label="发酵液样品编号">
                      <Input defaultValue={this.state.editData.f_fjypid } onChange={e => this.state.editData.f_fjypid = e.target.value } />
                  </Item>
                  <Item label="筛选菌株编号">
                      <Input defaultValue={this.state.editData.sxjj_id  } onChange={e => this.state.editData.sxjj_id = e.target.value } />
                  </Item>
                  <Item label="菌种保藏编号">
                      <Input defaultValue={this.state.editData.jzbc_id  } onChange={e => this.state.editData.jzbc_id = e.target.value } />
                  </Item>

                  <Item label="发酵日期" wrapperCol>
                    <DatePicker
                      format="YYYY-MM-DD HH:mm:ss"
                      defaultValue={moment(this.state.editData.ferment_time)}
                      onChange={(date, dateString) => this.state.editData.ferment_time = dateString}
                      style={{ width: "100%" }}
                      placeholder={[" ", ""]}
                    />
                  </Item>
                  <Item label="发酵批号">
                      <Input defaultValue={this.state.editData.ferment_batch  } onChange={e => this.state.editData.ferment_batch = e.target.value } />
                  </Item>
                  <Item label="萃取溶剂">
                      <Input defaultValue={this.state.editData.ce_cqrj  } onChange={e => this.state.editData.ce_cqrj = e.target.value } />
                  </Item>
                  <Item label="萃取部位">
                    <Select
                      mode="tags"
                      style={{ width: "100%" }}
                      defaultValue={this.state.editData.ce_cqbw}
                      onChange={value => this.state.editData.ce_cqbw = value[0]}
                      tokenSeparators={[","]}
                      showArrow={true}
                    >
                      <Option value="fjysq">发酵液上清</Option>
                      <Option value="fjyjt">发酵液菌体</Option>
                      <Option value="gtfjw">固体发酵物</Option>
                      <Option value="qtbw" disabled>
                        其他部位
                      </Option>
                    </Select>
                  </Item>
                </span>
                <span style={{ flex: 1 }}>
                  <Item label="已筛选模型">
                      <Input defaultValue={this.state.editData.m_id  } onChange={e => this.state.editData.m_id = e.target.value } />
                  </Item>
                  <Item label="粗提品制备时间">
                    <DatePicker
                      format="YYYY-MM-DD HH:mm:ss"
                      defaultValue={moment(this.state.editData.ce_time)}
                      onChange={(date, dateString) => this.state.editData.ce_time = dateString}
                      style={{ width: "100%" }}
                      placeholder={[" ", ""]}
                    />
                  </Item>
                  <Item label="粗提品制备人">
                      <Input defaultValue={this.state.editData.ce_person  } onChange={e => this.state.editData.ce_person = e.target.value } />
                  </Item>
                  <Item label="母板存放位置">
                      <Input defaultValue={this.state.editData.mom_place  } onChange={e => this.state.editData.mom_place = e.target.value } />
                  </Item>
                  <Item label="母板粗提品量/(微升)">
                      <Input defaultValue={this.state.editData.ce_mbctp } onChange={e => this.state.editData.ce_mbctp = e.target.value } />
                  </Item>
                  <Item label="子板存放位置">
                      <Input defaultValue={this.state.editData.son_place  } onChange={e => this.state.editData.son_place = e.target.value } />
                  </Item>
                  <Item label="子板粗提品量/(微升)">
                      <Input defaultValue={this.state.editData.ce_zbctp } onChange={e => this.state.editData.ce_zbctp = e.target.value } />
                  </Item>
                  <Item label="工作人员姓名">
                      <Input defaultValue={this.state.editData.worker } onChange={e => this.state.editData.worker = e.target.value } />
                  </Item>
                  <Button onClick={this.handleUpdate} type="primary" style={{marginLeft:'200px'}}>保存</Button>
                </span>
              </div>
            </Form>
          </Modal>
          <Modal
            title="添加粗提品"
            centered
            visible={this.state.showAddModal}
            onOk={() => this.showAddModal(false)}
            onCancel={() => this.showAddModal(false)}
            maskClosable={false}
          >
            <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
              <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                  <Item label="粗提品ID">
                      <Input onChange={e => this.state.newData.id = e.target.value } />
                  </Item>
                  <Item label="粗提品编号">
                      <Input onChange={e => this.state.newData.ctp_id = e.target.value } />
                  </Item>
                  <Item label="发酵液样品编号">
                      <Input onChange={e => this.state.newData.f_fjypid = e.target.value } />
                  </Item>
                  <Item label="筛选菌株编号">
                      <Input onChange={e => this.state.newData.sxjj_id = e.target.value } />
                  </Item>
                  <Item label="菌种保藏编号">
                      <Input onChange={e => this.state.newData.jzbc_id = e.target.value } />
                  </Item>

                  <Item label="发酵日期" wrapperCol>
                    <DatePicker
                      format="YYYY-MM-DD HH:mm:ss"
                      onChange={(date, dateString) => this.state.newData.ferment_time = dateString}
                      style={{ width: "100%" }}
                      placeholder={[" ", ""]}
                    />
                  </Item>
                  <Item label="发酵批号">
                      <Input onChange={e => this.state.newData.ferment_batch = e.target.value } />
                  </Item>
                  <Item label="萃取溶剂">
                      <Input onChange={e => this.state.newData.ce_cqrj = e.target.value } />
                  </Item>
                  <Item label="萃取部位">
                    <Select
                      mode="tags"
                      style={{ width: "100%" }}
                      onChange={value => this.state.newData.ce_cqbw = value[0]}
                      tokenSeparators={[","]}
                      showArrow={true}
                    >
                      <Option value="fjysq">发酵液上清</Option>
                      <Option value="fjyjt">发酵液菌体</Option>
                      <Option value="gtfjw">固体发酵物</Option>
                      <Option value="qtbw" disabled>
                        其他部位
                      </Option>
                    </Select>
                  </Item>
                </span>
                <span style={{ flex: 1 }}>
                  <Item label="已筛选模型">
                      <Input onChange={e => this.state.newData.m_id = e.target.value } />
                  </Item>
                  <Item label="粗提品制备时间">
                    <DatePicker
                      format="YYYY-MM-DD HH:mm:ss"
                      onChange={(date, dateString) => this.state.newData.ce_time = dateString}
                      style={{ width: "100%" }}
                      placeholder={[" ", ""]}
                    />
                  </Item>
                  <Item label="粗提品制备人">
                      <Input onChange={e => this.state.newData.ce_person = e.target.value } />
                  </Item>
                  <Item label="母板存放位置">
                      <Input onChange={e => this.state.newData.mom_place = e.target.value } />
                  </Item>
                  <Item label="母板粗提品量/(微升)">
                      <Input onChange={e => this.state.newData.ce_mbctp = e.target.value } />
                  </Item>
                  <Item label="子板存放位置">
                      <Input onChange={e => this.state.newData.son_place = e.target.value } />
                  </Item>
                  <Item label="子板粗提品量/(微升)">
                      <Input onChange={e => this.state.newData.ce_zbctp = e.target.value } />
                  </Item>
                  <Item label="工作人员姓名">
                      <Input onChange={e => this.state.newData.worker = e.target.value } />
                  </Item>
                  <Button onClick={this.handleAdd} type="primary" style={{marginLeft:'200px'}}>保存</Button>
                </span>
              </div>
            </Form>
          </Modal>
        </div>
        <Table
          rowSelection={rowSelection}
          bordered={true}
          columns={columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChange}
          // pagination={{ pageSize: 20 }} //设置第一页默认显示的列
          scroll={{ x: 4000, y: 300 }}
        />
      </div>
    );
  }
}
const WrapperedQuery_mediumForm = Form.create({
  name: "query medium"
})(Query_mediumForm);

class CrudeExtractInfo extends Component { 
  constructor(props) {
    super(props);
    this.state = {};
  }

  onSubmit = () => {
    const { form } = this.form.props;
    form.validateFields((errs, values) => {
      console.log(errs, values);
    });
  };
  render() {
    return (
      <Content>
        <WrapperedQuery_mediumForm
          wrappedComponentRef={ref => (this.form = ref)}
          onSubmit={this.onSubmit}
        />
      </Content>
    );
  }
}

export default CrudeExtractInfo;
